package javaParser;
/**
 * This class will read from a .xml file and 
 * send the output to Adler through RMI
 * 
 * @author Abdulla Al-Ali
 *
 */
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

//import Adler.DataInserter;


public class RMISender {
	
	private static final String INSERTSERVICE = "adlerInsert";
	Adler.DataInserter adlerInsert;
	
	public RMISender() {

	}
	
	public int Send(String fileName) {

		connectToRmi();
		if(insertXML(fileName)) {
			System.out.println("Data sent to remote service");
			return 0;
		} else {
			System.err.println("ERROR: couldn't send xml file to remote service");
			return -1;
		}
		
		//return 0;
	}
	
	private void connectToRmi() {
		
		System.out.println("Connecting to Adler");
		
		try{			
			Registry registry = LocateRegistry.getRegistry(Main.getHost());
			adlerInsert = (Adler.DataInserter)registry.lookup(INSERTSERVICE);
			System.out.println("Connected to the Server...");
		} catch (java.rmi.ConnectException e) {
			System.err.println("Error connecting to: \""+Main.getHost()+"\"");
			System.err.println("Make sure Adler is running on host. Exiting");
			System.exit(1);
		}
		catch(RemoteException e){
			System.out.println("Got an error at remote:");
			e.printStackTrace();
			System.exit(1);
		}
		catch(Exception e){
			System.out.println(e.toString());
			System.exit(1);
		}
	}
	
	public boolean insertXML(String filename){
		BufferedReader br;
		try{
			br = new BufferedReader(new FileReader(filename));
		}
		catch(FileNotFoundException e)
		{
			System.err.println("Couldn't find file " + filename);
			return false;  
		}

		String semanticData = "";
		String line;
		try{
			while((line = br.readLine()) != null)
			{
				semanticData += line;  
			}
		}
		catch(IOException e)
		{
			System.err.println("I/O Exception: " + e.getMessage() + " occurred while reading from " + filename );
			return false;  
		}

		try{
			int result = 0;
  		if(0 > (result = adlerInsert.Send(Main.getProject(), semanticData, "", "RDF/XML")) ){
				System.err.println("Failed to Insert data into DB. Error: " + result);
				return false;
			}
		}catch(RemoteException e){
			e.printStackTrace();
			System.exit(1);
		}
		return true;    
	}
	
}
